<?php
 /*
 * 1626cms 數據庫
 * ============================================================================
 * 版權所有: 1626網絡，并保留所有權利。
 * 網站地址: http://www.1626.com；
 * ----------------------------------------------------------------------------
 * 這不是一個自由軟件！您只能在不用于商業目的的前提下對程序代碼進行修改和
 * 使用；不允許對程序代碼以任何形式任何目的的再發布。
 * ============================================================================
*/
define('IN_QISHI', true);
require_once('../data/config.php');
require_once('./include/admin_common.inc.php');
require_once(ADMIN_ROOT_PATH.'include/admin_database.fun.php');
$act = !empty($_REQUEST['act']) ? trim($_REQUEST['act']) : 'backup';
$backup_dir="backup";
$smarty->assign('act',$act);
//備份
if($act == 'backup')
{
$pre = str_replace('_', '\_', $pre);
$smarty->assign('list',$db->getall("SHOW TABLES LIKE '$pre%'", MYSQL_NUM));
$smarty->assign('pageheader',"管理中心 - 數據庫 - 備份");
$smarty->display('admin_database_backup.htm');
}
//執行備份
if($act =='do_backup'){
if (!file_exists("../data/".$backup_dir."/"))showmsg("備份文件存放目錄data/".$backup_dir."不存在！",0);
if (!is_writable("../data/".$backup_dir."/"))showmsg("備份文件存放目錄data/".$backup_dir."不可寫！",0);
$limit_size = !empty($_REQUEST['limit_size']) ? intval($_REQUEST['limit_size']) : '2048'; 
$mysql_type = !empty($_REQUEST['mysql_type']) ? trim($_REQUEST['mysql_type']) : '';
$table_id = !empty($_REQUEST['table_id']) ? intval($_REQUEST['table_id']) : 0;
$file = !empty($_GET['file']) ? trim($_GET['file']) : date("Y_m_d_", time()) . get_rand_char(5);
$num = !empty($_GET['num']) ? intval($_GET['num']) : 1;
$pos = !empty($_GET['pos']) ? intval($_GET['pos']) : 0;
if ($_POST['tables'])
{
$tables = $_POST['tables'];
 @file_put_contents("../data/".$backup_dir."/temp.txt", serialize($_POST['tables']));
}
elseif ($_GET['table_id'])
{
$content = file_get_contents("../data/".$backup_dir."/temp.txt");
$tables = unserialize($content);
}
else
{
showmsg("您沒有選擇備份的表！",1);
}
$db_version = $db->dbversion();
$sql = '';
$version = QISHI_VERSION;
$add_time = date("Y-m-d H:i:s");
$sql .= "--VERSION:".$version."\r\n".
"--Mysql VERSION:".$db_version."\r\n".
"--Create time:".$add_time."\r\n";
$count = count($tables);
for($i = $table_id; $i < $count; $i++)
{
	$table = $tables[$i];
	if ($pos == 0)
	{
	$table_sql = write_head($table);
	$table_sql = preg_replace('/AUTO_INCREMENT=([0-9]+)(\s+)/', '', $table_sql);
	$table_sql1 = substr($table_sql, 0, strrpos($table_sql, ')', 25)+1);
		if ($mysql_type == 'mysql40' && $db_version > 4.0)
		{
		$s = "TYPE=MyISAM;\r\n";
		$table_sql = $table_sql1 . $s;
		}
		elseif($mysql_type == 'mysql41' && $db_version < 4.1)
		{
		$s = "ENGINE=MyISAM DEFAULT CHARSET=".QISHI_CHARSET.";\r\n";
		$table_sql = $table_sql1 . $s;
		}
		else
		{
		$table_sql .= ";\r\n";
		}
	}
$result = $db->query("SELECT * FROM " . $table);
$field_num = $db->num_fields($result);
$row_count = $db->getfirst("SELECT COUNT(*) FROM " . $table);
$j = 0;
while ($row = $db->fetch_array($result, MYSQL_NUM))
{
	if ($j < $pos)
	{
	 $j++;
	continue;
	}
		$table_sql .= "INSERT INTO `".$table."` VALUES (";
		for($m=0;$m<$field_num;$m++)
		{
		$table_sql .= "'" . $db->escape_string($row[$m]) . "',";
		}
		$table_sql = substr($table_sql,0,-1).");\r\n";				
	if (strlen($sql.$table_sql) >= $limit_size * 1000)
	{
		if (!write_file("../data/".$backup_dir."/".$file.'_'.$num.'.sql', $sql))
		{
		showmsg('備份數據庫卷-'.$num.'失敗',0);
		}
		if ($j == $row_count-1)
		{
		$i++;
		}
		$link[0]['text'] = "程序將自動繼續...";
        $link[0]['href'] = "admin_database.php?act=do_backup&limit_size=".$limit_size."&mysql_type=".$mysql_type."&file=".$file."&num=".($num+1)."&table_id=".$i."&pos=".$j;
		showmsg('文件'.$file.'_'.$num.'.sql 成功備份。程序將自動繼續...',1,$link,true,1);
		exit();
	}else{
		$sql .= $table_sql;
		$table_sql = '';
	}
	$j++;
}
$pos = 0;
if (strlen($sql.$table_sql) >= $limit_size * 1000)
{
if (!write_file("../data/".$backup_dir."/".$file.'_'.$num.'.sql', $sql))
{
showmsg('備份數據庫卷-'.$num.'失敗',0);
}
$link[0]['text'] = "程序將自動繼續...";
$link[0]['href'] = "admin_database.php?act=do_backup&limit_size=".$limit_size."&mysql_type=".$mysql_type."&file=".$file."&num=".($num+1)."&table_id=".($i+1);
showmsg('文件' . $file . '_' . $num.'.sql 成功備份。程序將自動繼續...', 1,$link,true,1);
exit();
}
elseif ($i == $count-1)
{
if (!write_file("../data/".$backup_dir."/".$file.'_'.$num.'.sql', $sql))
{
showmsg('備份數據庫卷-'.$num.'失敗');
}
@unlink("../data/".$backup_dir."/temp.txt");
$link[0]['text'] = "查看備份文件";
$link[0]['href'] = "?act=restore";
showmsg('數據庫備份成功',2,$link);
}
elseif ($j == 0)
{
$sql .= $table_sql;
}
}
}
//列出所有備份文件
if($act =='restore'){
if (!file_exists("../data/".$backup_dir."/"))showmsg("備份文件存放目錄data/backup不存在！",0);
$data_backup_list = $file_info = array();
$dir = opendir('../data/'.$backup_dir);
while($file = readdir($dir))
{
if(strpos($file,'.sql')!==false && !in_array(substr($file, 0, 16).'.sql', $data_backup_list))
{
$data_backup_list[] = substr($file, 0, 16).'.sql';
}
}
foreach($data_backup_list as $key => $file)
{
if (file_exists("../data/".$backup_dir."/".$file))
{
$sqlfile_info_arr = get_sqlfile_info("../data/".$backup_dir."/".$file);
$file_info[$key]['file_size'] = filesize("../data/".$backup_dir."/".$file);
}
else
{
$sqlfile_info_arr = get_sqlfile_info("../data/".$backup_dir."/".substr($file, 0, 16).'_1.sql');
$i = 1;
while (file_exists("../data/".$backup_dir."/".substr($file, 0, 16).'_'.$i.'.sql'))
{
$file_info[$key]['file_size'] += filesize("../data/".$backup_dir."/".substr($file, 0, 16).'_'.$i.'.sql');
$i++;
}
}
$file_info[$key]['file_name'] = substr($file,0);
$file_info[$key]['74cms_ver'] = $sqlfile_info_arr['74cms_ver'];
$file_info[$key]['mysql_ver'] = $sqlfile_info_arr['mysql_ver'];
$file_info[$key]['add_time'] = $sqlfile_info_arr['add_time'];
}
$smarty->assign('pageheader',"管理中心 - 數據庫 - 恢復");
$smarty->assign('list',array_reverse($file_info));
$smarty->display('admin_database_restore.htm');
}
//刪除備份
if($act =='del'){
$file_name = !empty($_GET['file_name']) ? trim($_GET['file_name']) : '';
$file_name = substr($file_name, 0, -4);
if ($handle = opendir("../data/".$backup_dir))
{
while (false !== $file = readdir($handle))
{
if (strpos($file, $file_name) !== false && $file != 'index.htm' && $file != '.' && $file != '..')
{
$sql_file[] = $file;
}
}
}
foreach ($sql_file as $val)
{
@unlink("../data/".$backup_dir."/" . $val);
}
showmsg('刪除備份文件成功',2);
}
//導入備份
if($act =='import'){
$file_name = !empty($_GET['file_name']) ? trim($_GET['file_name']) : '';
$file_name = substr($file_name, 0, -4);
if ($handle = opendir("../data/".$backup_dir))
{
while (false !== $file = readdir($handle))
{
if (strpos($file, $file_name) !== false && $file != 'index.htm' && $file != '.' && $file != '..')
{
$backup_file[] = $file;
}
}
}
else
{
showmsg('該備份文件不存在!',0);
}
$file ="../data/".$backup_dir."/".$backup_file[0];
$file_info = get_sqlfile_info($file);
if($file_info['74cms_ver'] != QISHI_VERSION)
{
showmsg('當前程序與備份程序版本不一致');
}
foreach ($backup_file as $file)
{
$file = "../data/".$backup_dir."/".$file;
$file = array_filter(file($file), 'remove_comment');
$file = str_replace("\r", "\n", implode('', $file));
$arr = explode(";\n", trim($file));
$arr_count = count($arr);
for($i = 0; $i < $arr_count; $i++)
{
$arr[$i] = trim($arr[$i]);
if (!empty($arr[$i]))
{
if ((strpos($arr[$i], 'CREATE TABLE') !== false) && (strpos($arr[$i], 'DEFAULT CHARSET='.str_replace('-', '', QISHI_CHARSET) )!== false))
{
$arr[$i] = str_replace('DEFAULT CHARSET='. str_replace('-', '', QISHI_CHARSET), '', $arr[$i]);
}
!$db->query($arr[$i])?showmsg('還原失敗',0):"";
}
}
}
showmsg('還原數據庫成功',2);
}
?>
